#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

import redirect as app


class GaeTestCase(unittest.TestCase):
  def setUp(self, *args, **kwargs):
    self.clear_datastore()
    super(GaeTestCase, self).setUp(*args, **kwargs)

  @staticmethod
  def clear_datastore():
    from google.appengine.api import apiproxy_stub_map, datastore_file_stub
    from google.appengine.api import memcache

    # See http://code.google.com/p/gaeunit/issues/detail?id=15 for clue.
    for key in ['datastore', 'datastore_v3']:
      # W0212: 23,16:GaeTestCase.clear_datastore: Access to a protected member
      # _APIProxyStubMap__stub_map of a client class
      # pylint: disable=W0212
      # E1101: 50,16:GaeTestCase.clear_datastore: Instance of 'APIProxyStubMap'
      # has no '_APIProxyStubMap__stub_map' member
      # pylint: disable=E1101
      if key in apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map:
        # W0212: 24,12:GaeTestCase.clear_datastore: Access to a protected
        # member _APIProxyStubMap__stub_map of a client class
        # pylint: disable=W0212
        # E1101: 54,12:GaeTestCase.clear_datastore: Instance of
        # 'APIProxyStubMap' has no '_APIProxyStubMap__stub_map' member
        # pylint: disable=E1101
        del apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map[key]

    # Use a fresh stub datastore.
    stub = datastore_file_stub.DatastoreFileStub(
        app.APP_NAME, '/dev/null', '/dev/null')
    apiproxy_stub_map.apiproxy.RegisterStub('datastore', stub)

    # Flush memcache.
    memcache.flush_all()


class RedirectTestCase(GaeTestCase):
  def redirect_helper(self, path):
    from webtest import TestApp
    testapp = TestApp(app.application)
    response = testapp.get(path)
    self.assertEquals('302 Moved Temporarily', response.status)
    self.assertEquals('', response.body)
    return response

  def test_main_page_redirect(self):
    page = self.redirect_helper('/')
    self.assertEquals(page.headers['Location'],
        'http://code.google.com/p/chromium/issues/list')

  def test_issue_page_redirect(self):
    page = self.redirect_helper('/123456')
    self.assertEquals(page.headers['Location'],
        'http://code.google.com/p/chromium/issues/detail?id=123456')
    
  def test_username_page_redirect(self):
    page = self.redirect_helper('/~agable')
    self.assertEquals(page.headers['Location'],
        'http://code.google.com/p/chromium/issues/list?'
        'can=2&q=owner:agable&cells=tiles&colspec='
        'ID+Pri+Mstone+ReleaseBlock+OS+Area+Feature+Status+Owner+Summary')
